/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
	struct Cmp {
		bool operator()(const Interval& a, const Interval& b) const {
			return a.start < b.start;
		}
	};

	vector<Interval> merge(vector<Interval> &intervals) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    	sort(intervals.begin(), intervals.end(), Cmp());
		vector<Interval> result;
        int n = intervals.size();

		for (int i = 0; i < n; ) {
			int j = i;
			int end = intervals[i].end;
			while (j < n && intervals[j].start <= end) {
				end = max(end, intervals[j].end);
				++j;
			}
			result.push_back(Interval(intervals[i].start, end));
			i = j;
		}
		return result;
    }
};